const path = require("path");
const fs = require("fs"); // 引入fs模块
const crypto = require("crypto");

/**
 * 获得内容的hash值
 *
 * @param {String} content 文件内容
 * @param {String} encoding 文件的编码，例如：'utf8' 等
 * @param {String} type hash算法，例如：'md5'、'sha1'、'sha256'、'sha512' 等
 * @returns {String}
 * @date   2015-11-15
 */
function getHash(content, encoding, type) {
  return crypto
    .createHash(type)
    .update(content, encoding)
    .digest("hex");
}

/**
 * 获得文件的hash值
 *
 * @param {String} filePath 文件路径
 * @returns {String}
 * @date   2015-11-15
 */
function getHashOfFile(filePath) {
  return getHash(fs.readFileSync(filePath, "utf8"), "utf8", "md5");
}

function removeDir(path) {
  var files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function(file, index) {
      var curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) {
        // recurse
        removeDir(curPath);
      } else {
        // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}

function normalizePath(configDir, _path) {
  if (_path && path.isAbsolute(_path)) {
    return _path;
  }
  return path.resolve(configDir, _path);
}

function load(path) {
  return require(path);
}
module.exports = {
  normalizePath,
  load,
  removeDir,
  getHash: getHash,
  getHashOfFile: getHashOfFile
};
